/**
 * Created by xiaom on 2016/10/29.
 */
import React, {Component} from 'react';
import Functions from './components/Functions/index';
import Header from './components/Header/index';
import {Footer, shouldUpdate} from '../../components/index';
import querystring from 'querystring';
import wechat from '../../config/wechat.config';
import axios from 'axios';
import URI from 'urijs';
import Toast from '../../components/Toast/index';
import PureRenderMixin from 'react-addons-pure-render-mixin';

const storage = window.localStorage;
const session = window.sessionStorage;
const WeChat_UserInfo = storage.getItem('WeChat_UserInfo');

function generateGetCodeUrl(redirectURL) {
  return new URI("https://open.weixin.qq.com/connect/oauth2/authorize")
    .addQuery("appid", wechat.APP_ID)
    .addQuery("redirect_uri", redirectURL)
    .addQuery("response_type", "code")
    .addQuery("scope", "snsapi_userinfo")
    .addQuery("response_type", "code")
    .hash("wechat_redirect")
    .toString();
}

export default class Home extends Component {

  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
  }

  state = {
    WeChat_UserInfo: {
      'headimgurl': 'http://wx.qlogo.cn/mmopen/Cjm4uX7UWWqEBC1BGAkHepuG1TdfmialtPHVWlXWlZVTXscWB3X5moYkhrKFEUS47gRvscic1zpibg9zeBMzNQk9P3kBbnlChgY/0',
      'nickname': 'mak'
    },
    //TODO
    Page_Loading: false
  };

  wechatAuth() {
    const _this = this;
    if (WeChat_UserInfo == null || WeChat_UserInfo == undefined || WeChat_UserInfo == '') {
      const uri = new URI(document.location.href);
      const query = uri.query(true);
      const {code} = query;
      if (code) {
        axios.post('/netmaker/backstage/index.php?g=api&m=WeChat&a=getOpenId', querystring.stringify({
          code: code
        })).then(function (response) {
          if (response.data.code == 200) {
            session.setItem('WeChat_Info', response.data.data);
            _this.getUserInfo(JSON.parse(response.data.data));
          } else {
            alert(response.message);
          }
        }).catch(function (error) {
          alert(error);
          return false;
        });
      } else {
        document.location = generateGetCodeUrl(document.location.href);
      }
    } else {
      _this.setState({
        'Page_Loading': false,
        'WeChat_UserInfo': JSON.parse(WeChat_UserInfo)
      });
      _this.state.Page_Loading = false;
    }
  }

  getUserInfo(WeChat_Info) {
    const _this = this;
    axios.post('/netmaker/backstage/index.php?g=api&m=WeChat&a=getUserInfo', querystring.stringify({
      access_token: WeChat_Info.access_token,
      openid: WeChat_Info.openid,
    })).then(function (response) {
      if (response.data.code == 200) {
        _this.setState({'WeChat_UserInfo': JSON.parse(response.data.data)});
        storage.setItem('WeChat_UserInfo', response.data.data);
      } else {
        alert(response.message);
      }
      _this.setState({'Page_Loading': false});
    }).catch(function (error) {
      _this.setState({'Page_Loading': false});
      alert(error);
      return false;
    });
  }

  componentDidMount() {
    //todo 暂时注释
    // this.wechatAuth();
  }

  shouldComponentUpdate(nextProps = {}, nextState = {}) {
    return shouldUpdate(this, nextProps, nextState);
  }

  render() {
    const _this = this;
    return (
      <div>
        <Toast message="正在加载123123" show={_this.state.Page_Loading}/>
        <Header avatar={_this.state.WeChat_UserInfo.headimgurl} nickname={_this.state.WeChat_UserInfo.nickname}/>
        <Functions/>
        <Footer/>
      </div>
    );
  }
}
